import cloud from '@lafjs/cloud';
let appId = "wx267097d752f5c3fd"
let secret = "3fa70dc6ee45b4e90b2ab0fdc24dd778"

export default async function (ctx: FunctionContext) {
  const { url } = ctx.body;

  // 获取微信 JS-SDK 的 config 数据
  const configData = await getWechatConfig(url);

  return configData;
}

async function getWechatConfig(url: string) {
  // 调用微信 API 获取 config 数据
  const { data } = await cloud.fetch('https://api.weixin.qq.com/cgi-bin/token', {
    method: 'GET',
    params: {
      grant_type: 'client_credential',
      appId,
      secret,
    },
  });

  if (data.hasOwnProperty("errcode")) return cloud.utils.requestReturn({ code: 500, msg: data.errmsg })

  let { access_token } = data

  const configData = await cloud.fetch('https://api.weixin.qq.com/cgi-bin/ticket/getticket', {
    method: 'GET',
    params: { access_token, type: 'jsapi' },
  });
  const { ticket } = configData.data;
  if (!ticket) return cloud.utils.requestReturn({ code: 500, msg: "ticket未获取" })

  // 生成随机字符串和时间戳
  const noncestr = Math.random().toString(36).substr(2, 15);
  const timestamp = Math.floor(Date.now() / 1000);
  const signature = generateSignature(ticket, noncestr, timestamp, url);

  // 返回 config 数据
  let obj = {
    debug: false,
    appId,
    timestamp,
    nonceStr: noncestr,
    signature,
  };
  return cloud.utils.requestReturn({ data: obj })
}

function generateSignature(ticket: string, noncestr: string, timestamp: number, url: string) {
  const string = `jsapi_ticket=${ticket}&noncestr=${noncestr}&timestamp=${timestamp}&url=${url}`;
  const signature = cloud.sha1Func(string);
  return signature;
}